package com.atguigu.gmall.product.controller;

import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class TestComPare {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
      /*  //创建一个无参无返回值的对象
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("-----------runAsync无返回值------------");
        });
        //创建一个无参有返回值的对象
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
//            int i= 1/0;会显示算数异常
            return 1024;
          //这是串行化的方法：当一个线程依赖另一个线程时，获取上一个任务返回的结果，并返回当前任务的返回值
        }).thenApply(new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer integer) {
                System.out.println("thenApply =\t" + integer);
                return integer*2;
            }
            //当计算完成时继续执行以下的方法
        }).whenComplete(new BiConsumer<Integer, Throwable>() {
            @Override
            public void accept(Integer integer, Throwable throwable) {
                System.out.println("integer =\t" + integer);      //1024
                System.out.println("throwable =\t" + throwable);  //null
            }
        }).exceptionally(throwable -> {
            System.out.println(throwable);
            return 404;
        });

        System.out.println(completableFuture.get());
        System.out.println(future.get());*/
        //创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                100,
                3,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3));


        //创建一个线程A返回 helloA   supplyAsync有返回值
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> {
            return "helloA";
        },threadPoolExecutor);
        //创建一个线程B返回 helloB
        CompletableFuture<Void> futureB = futureA.thenAcceptAsync((s) -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B:\t" + s);
        },threadPoolExecutor);

        //创建一个线程C返回 helloC
        CompletableFuture<Void> futureC = futureA.thenAcceptAsync((s) -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("C:\t" + s);
        },threadPoolExecutor);

        System.out.println(futureB.get());
        System.out.println(futureC.get());

        //释放资源---
        threadPoolExecutor.shutdown();
    }
}
